package com.example.campuslink.commen.adpter

import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.core.CoreAdapter
import com.example.campuslink.commen.core.CoreViewHolder
import com.example.campuslink.commen.interfaces.CommendPublic
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpKey
import com.example.campuslink.databinding.AdapterInvitationCommendBinding
import com.example.campuslink.model.CommendInfoData
import com.example.campuslink.viewModel.InvitationDetailViewModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class InvitationCommendAdapter(
    vm: InvitationDetailViewModel,
    val commendPublic: CommendPublic
) : CoreAdapter<AdapterInvitationCommendBinding, InvitationDetailViewModel, CommendInfoData>(
    BR.data,
    BR.viewModel,
    vm
) {
    private val childrenAdapters = mutableMapOf<Int, InvitationChildrenCommendAdapter>()
    private var childrenAdapter: InvitationChildrenCommendAdapter? = null
    private val childCommendObserver = Observer<Map<Int, MutableList<CommendInfoData>>> { map ->
        map?.forEach { (position, list) ->
            childrenAdapters[position]?.setListData(list)
        }
    }

    init {
        childrenAdapter = InvitationChildrenCommendAdapter(vm, commendPublic)
        mViewModel?.childCommendList?.observeForever(childCommendObserver)
        mViewModel?.getChildCommend()
    }

    private fun transformTime(time: Long): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val formattedTime = sdf.format(Date(time))
        return formattedTime
    }

    override fun getItemLayoutId(viewType: Int): Int {
        return R.layout.adapter_invitation_commend
    }

    override fun onBindViewHolder(holder: CoreViewHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        Glide.with(holder.itemView.context).load(mListData[position].userImg)
            .error(R.drawable.ic_empty)
            .apply(RequestOptions.circleCropTransform())
            .into(holder.binding.root.findViewById<ImageView>(R.id.iv_userImg))
        holder.binding.root.findViewById<TextView>(R.id.tv_userName).text =
            mListData[position].userName
        holder.binding.root.findViewById<TextView>(R.id.tv_content).text =
            mListData[position].commendTable?.commentContent + "\t" + transformTime(
                mListData[position].commendTable?.data ?: 0
            )
        Glide.with(holder.itemView.context).load(mListData[position].commendTable?.contentImage)
            .into(holder.binding.root.findViewById<ImageView>(R.id.iv_contentImg))
        holder.binding.root.findViewById<TextView>(R.id.tv_like_count).text =
            mListData[position].commendTable?.loveNumber?.size.toString()

        // 子评论处理
        val childRecyclerView =
            holder.binding.root.findViewById<RecyclerView>(R.id.rv_children_answer)

        val childAdapter = childrenAdapters.getOrPut(position) {
            InvitationChildrenCommendAdapter(mViewModel!!, commendPublic).apply {
                // 设置初始数据（可能为emptyList）
                setListData(mViewModel?.childCommendList?.value?.get(position) ?: emptyList())
            }
        }


        if (mListData[position].commendTable?.loveNumber?.contains(
                Sp.getString(
                    holder.itemView.context,
                    SpKey.USER_NUMBER.key,
                    ""
                )
            ) ?: false
        ) {
            Glide.with(holder.itemView.context).load(R.drawable.ic_collected)
                .into(holder.binding.root.findViewById<ImageView>(R.id.iv_like))
        } else {
            Glide.with(holder.itemView.context).load(R.drawable.ic_collect)
                .into(holder.binding.root.findViewById<ImageView>(R.id.iv_like))
        }
        holder.binding.root.findViewById<ImageView>(R.id.iv_like).setOnClickListener({
            if (mListData[position].commendTable?.loveNumber?.contains(
                    Sp.getString(
                        holder.itemView.context,
                        SpKey.USER_NUMBER.key,
                        ""
                    )
                ) ?: false
            ) {
                mViewModel?.removeLikeCommend(
                    true, mListData[position].commendTable?.id ?: 0,
                    mListData[position].commendTable?.commentUserNumber ?: "",
                    position
                )
            } else {
                mViewModel?.addLikeCommend(
                    true,
                    mListData[position].commendTable?.id ?: 0,
                    mListData[position].commendTable?.commentUserNumber ?: "",
                    position
                )
            }

            notifyDataSetChanged()
        })

        holder.binding.root.findViewById<TextView>(R.id.tv_like_count).text =
            mListData[position].commendTable?.loveNumber?.size.toString()

        childRecyclerView.apply {
            adapter = childAdapter
            layoutManager = LinearLayoutManager(context)
            setHasFixedSize(true)
        }
        holder.binding.root.findViewById<TextView>(R.id.tv_reCommend).setOnClickListener({
            commendPublic.publicCommend(
                position,
                mListData[position].commendTable?.commentUserNumber ?: ""
            )
        })
        holder.binding.root.setOnClickListener({
            commendPublic.publicCommend(position, "")
        })
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        mViewModel?.childCommendList?.removeObserver(childCommendObserver)
    }


}